package main

import (
	"container/heap"
	"fmt"
)

/*
优先级队列，对于结构体排序，按照年龄升序
*/

type stu struct {
	name string
	age  int
}
type Stu []stu

/*
重写sort.Interface方法
*/

func (t *Stu) Len() int {
	return len(*t) //
}

func (t *Stu) Less(i, j int) bool {
	return (*t)[i].age < (*t)[j].age
}

func (t *Stu) Swap(i, j int) {
	(*t)[i], (*t)[j] = (*t)[j], (*t)[i]
}

/*
重写heap.Interface方法
*/

func (t *Stu) Push(x interface{}) {
	*t = append(*t, x.(stu))
}

func (t *Stu) Pop() interface{} {
	n := len(*t)
	x := (*t)[n-1]
	*t = (*t)[:n-1]
	return x
}

func main() {
	student := &Stu{{"Amy", 21}, {"Dav", 15}, {"Spo", 22}, {"Reb", 11}}
	heap.Init(student)
	one := stu{"hund", 9}
	heap.Push(student, one)
	fmt.Println("队列顶部的元素: ", (*student)[0])

	for student.Len() > 0 {
		fmt.Printf("%v\n", heap.Pop(student))
	}
	/*
		队列顶部的元素:  {hund 9}
		{hund 9}
		{Reb 11}
		{Dav 15}
		{Amy 21}
		{Spo 22}

	*/
}
